#include <TFT_eSPI.h>
#include <SPI.h>

// EC11编码器引脚定义（避开被占用的2、3、6、7、10）
#define ENCODER_CLK_PIN 1     // S1 - 编码器CLK信号（GPIO1）
#define ENCODER_DT_PIN 4      // S2 - 编码器DT信号（GPIO4）
#define ENCODER_SW_PIN 5      // KEY - 编码器按键（GPIO5）

// TFT屏幕初始化
TFT_eSPI tft = TFT_eSPI();

// 编码器状态变量
volatile int encoderPos = 0;
int lastEncoderPos = 0;
unsigned long lastButtonPressTime = 0;
const unsigned long debounceDelay = 50;
bool buttonPressed = false;

// 菜单结构定义
struct MenuItem {
  const char* title;
  void (*action)();
  struct MenuItem* submenu;
  int submenuCount;
};

// 菜单项函数原型
void mainMenuAction();
void settingsMenuAction();
void displaySettingsAction();
void brightnessAction();
void contrastAction();
void networkSettingsAction();
void wifiAction();
void bluetoothAction();
void infoAction();
void aboutAction();
void versionAction();

// 菜单项定义
MenuItem brightnessItem = {"LIANDUTIAOJIE", brightnessAction, nullptr, 0};
MenuItem contrastItem = {"DUIBIDUTIAOJIE", contrastAction, nullptr, 0};
MenuItem displaySettings = {"XIANSHISHEZHI", displaySettingsAction, &brightnessItem, 2};

MenuItem wifiItem = {"WiFiSHEZHI", wifiAction, nullptr, 0};
MenuItem bluetoothItem = {"NANYASHEZHI", bluetoothAction, nullptr, 0};
MenuItem networkSettings = {"WANGLUOSHEZHI", networkSettingsAction, &wifiItem, 2};

MenuItem aboutItem = {"GUANYU", aboutAction, nullptr, 0};
MenuItem versionItem = {"BANBEN", versionAction, nullptr, 0};
MenuItem infoItem = {"XITONG", infoAction, &aboutItem, 2};

MenuItem settingsItems[] = {displaySettings, networkSettings};
MenuItem mainItems[] = {
  {"HEMO", mainMenuAction, nullptr, 0},
  {"SHEZHI", settingsMenuAction, settingsItems, 2},
  {"XINXI", infoAction, &aboutItem, 2}
};

// 当前菜单状态
MenuItem* currentMenu = mainItems;
int currentSelection = 0;
int menuItemCount = 3;

// 前置声明编码器中断函数
void IRAM_ATTR readEncoder();

// 初始化编码器
void setupEncoder() {
  pinMode(ENCODER_CLK_PIN, INPUT_PULLUP);
  pinMode(ENCODER_DT_PIN, INPUT_PULLUP);
  pinMode(ENCODER_SW_PIN, INPUT_PULLUP);
  
  // 配置编码器CLK引脚的中断
  attachInterrupt(digitalPinToInterrupt(ENCODER_CLK_PIN), readEncoder, CHANGE);
}

// 绘制菜单
void drawMenu() {
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_YELLOW, TFT_BLACK);
  tft.setTextSize(2);
  tft.setCursor(10, 10);
  tft.println("ESP32-C3CAIDANXITONG");
  tft.drawFastHLine(0, 30, tft.width(), TFT_DARKGREY);
  
  // 绘制菜单项
  tft.setTextSize(1.5);
  for (int i = 0; i < menuItemCount; i++) {
    if (i == currentSelection) {
      // 选中项样式
      tft.fillRect(10, 50 + i * 30, tft.width() - 20, 25, TFT_DARKGREY);
      tft.setTextColor(TFT_RED, TFT_DARKGREY);
    } else {
      // 普通项样式
      tft.setTextColor(TFT_WHITE, TFT_BLACK);
    }
    tft.setCursor(20, 55 + i * 30);
    tft.print("> ");
    tft.println(currentMenu[i].title);
  }
}

// 编码器中断服务函数
void IRAM_ATTR readEncoder() {
  static int lastCLK = HIGH;
  int currentCLK = digitalRead(ENCODER_CLK_PIN);
  
  // 仅在CLK下降沿处理，减少中断次数
  if (currentCLK == LOW && lastCLK == HIGH) {
    if (digitalRead(ENCODER_DT_PIN) == LOW) {
      encoderPos++;  // 顺时针旋转
    } else {
      encoderPos--;  // 逆时针旋转
    }
  }
  lastCLK = currentCLK;
}

// 编码器按键消抖
bool readEncoderButton() {
  static bool lastButtonState = HIGH;
  bool currentButtonState = digitalRead(ENCODER_SW_PIN);
  
  if (lastButtonState == HIGH && currentButtonState == LOW) {
    lastButtonPressTime = millis();
  }
  
  if (lastButtonState == LOW && currentButtonState == HIGH && 
      (millis() - lastButtonPressTime) > debounceDelay) {
    lastButtonState = currentButtonState;
    return true;  // 按键有效
  }
  
  lastButtonState = currentButtonState;
  return false;
}

// 菜单项动作函数
void mainMenuAction() {
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_WHITE);
  tft.setTextSize(2);
  tft.setCursor(10, 50);
  tft.println("HELOO");
  delay(1500);
  drawMenu();
}

void settingsMenuAction() {
  currentMenu = settingsItems;
  menuItemCount = 2;
  currentSelection = 0;
  drawMenu();
}

void displaySettingsAction() {
  currentMenu = &brightnessItem;
  menuItemCount = 2;
  currentSelection = 0;
  drawMenu();
}

void brightnessAction() {
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_WHITE);
  tft.setTextSize(2);
  tft.setCursor(10, 50);
  tft.println("LIANDUTIAOJIE");
  delay(1500);
  drawMenu();
}

void contrastAction() {
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_WHITE);
  tft.setTextSize(2);
  tft.setCursor(10, 50);
  tft.println("DUIBIDUTIAOJIE");
  delay(1500);
  drawMenu();
}

void networkSettingsAction() {
  currentMenu = &wifiItem;
  menuItemCount = 2;
  currentSelection = 0;
  drawMenu();
}

void wifiAction() {
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_WHITE);
  tft.setTextSize(2);
  tft.setCursor(10, 50);
  tft.println("WiFiSHEZHI");
  delay(1500);
  drawMenu();
}

void bluetoothAction() {
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_WHITE);
  tft.setTextSize(2);
  tft.setCursor(10, 50);
  tft.println("LANYASHEZHI");
  delay(1500);
  drawMenu();
}

void infoAction() {
  currentMenu = &aboutItem;
  menuItemCount = 2;
  currentSelection = 0;
  drawMenu();
}

void aboutAction() {
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_WHITE);
  tft.setTextSize(2);
  tft.setCursor(10, 50);
  tft.println("GUANYUXITONG");
  tft.setTextSize(1.5);
  tft.setCursor(10, 80);
  tft.println("ESP32-C3DUOJICAIDANYANSHI");
  tft.setCursor(10, 110);
  tft.print("shiyongEC11BIANMAQIKONGZHI");
  delay(2000);
  drawMenu();
}

void versionAction() {
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_WHITE);
  tft.setTextSize(2);
  tft.setCursor(10, 50);
  tft.println("BANBENXINXI");
  tft.setTextSize(1.5);
  tft.setCursor(10, 80);
  tft.println("GUJIANBANBEN: v1.0.0");
  tft.setCursor(10, 110);
  tft.println("CAIDANXITONG");
  delay(2000);
  drawMenu();
}

// 返回上级菜单
void goBack() {
  if (currentMenu == settingsItems || currentMenu == &wifiItem || 
      currentMenu == &brightnessItem || currentMenu == &aboutItem) {
    currentMenu = mainItems;
    menuItemCount = 3;
  }
  currentSelection = 0;
  drawMenu();
}

// 初始化
void setup() {
  Serial.begin(115200);
  
  // 初始化TFT屏幕
  tft.init();
  tft.setRotation(1);  // 设置屏幕方向（0-3可选）
  tft.fillScreen(TFT_BLACK);
  
  // 初始化编码器
  setupEncoder();
  
  // 显示欢迎信息
  tft.setTextColor(TFT_WHITE);
  tft.setTextSize(2);
  tft.setCursor(10, 100);
  tft.println("CHUSHIHUAZHGONG...");
  delay(1000);
  
  // 绘制主菜单
  drawMenu();
}

// 主循环
void loop() {
  // 处理编码器旋转
  if (encoderPos != lastEncoderPos) {
    currentSelection += (encoderPos > lastEncoderPos) ? 1 : -1;
    // 循环选择（超出范围时回到首尾）
    currentSelection = (currentSelection + menuItemCount) % menuItemCount;
    lastEncoderPos = encoderPos;
    drawMenu();  // 更新显示
  }
  
  // 处理编码器短按（进入子菜单或执行动作）
  if (readEncoderButton()) {
    buttonPressed = true;
    if (currentMenu[currentSelection].submenu != nullptr) {
      // 进入子菜单
      currentMenu = currentMenu[currentSelection].submenu;
      menuItemCount = currentMenu[currentSelection].submenuCount;
      currentSelection = 0;
      drawMenu();
    } else if (currentMenu[currentSelection].action != nullptr) {
      // 执行当前项动作
      currentMenu[currentSelection].action();
    }
  }
  
  // 处理编码器长按（返回上级菜单，长按1秒触发）
  static unsigned long pressStartTime = 0;
  if (digitalRead(ENCODER_SW_PIN) == LOW) {
    if (pressStartTime == 0) pressStartTime = millis();
    else if (millis() - pressStartTime > 1000 && !buttonPressed) {
      goBack();
      pressStartTime = 0;
      while (digitalRead(ENCODER_SW_PIN) == LOW);  // 等待按键释放
    }
  } else {
    pressStartTime = 0;
    buttonPressed = false;
  }
  
  delay(10);  // 降低CPU占用
}